#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Project  :main.py
# @Date     :2021/1/23 8:23 下午
# @Author   :JIAN LI
# @Email    :lijianjlu@126.com

import cv2 as cv
import numpy as np
import sys
import getopt

def face_dect(img,cascade):
    """ 定义人脸检测函数 """
    rects = cascade.detectMultiScale(img,scaleFactor = 1.3,
                                     minNeighbors = 4,
                                     minSize = (30,30),
                                     flags = cv.CASCADE_SCALE_IMAGE)
    if len(rects) == 0:
        return []
    else:
        rects[:,2:] += rects[:,:2]
        return rects

def draw_rects(img,rect,color):
    """ 在图像中绘制人脸方框 """
    for x1, y1, x2, y2 in rect:
        cv.rectangle(img, (x1,y1), (x2,y2), color, 2)

if __name__ == '__main__':
    cascade_fn = "./haarcascades/haarcascade_frontalface_alt.xml" # 定义人脸检测模版
    #nested_fn = "./haarcascade_eye.xml" # 定义人眼检测模版
    img_path = "imgs/1.jpg" # 定义待处理图像

    cascade = cv.CascadeClassifier(cascade_fn)
    #nested = cv.CascadeClassifier(nested_fn)

    img = cv.imread(img_path) # 读取图像

    rects = face_dect(img,cascade) # 检测图像中人脸位置
    draw_rects(img, rects, (0, 255, 255)) # 将人脸位置画出

    cv.imshow('Face detect result',img) # 显示图像
    cv.waitKey(0)
    cv.destroyAllWindows()

